"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardFooter } from "@/components/ui/card";
import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";
import axios from "axios";

import { Search } from "lucide-react";
import Link from "next/link";

// Simulated product data
interface proitem {
  id: 1;
  name: "Organic Bananas";
  price: 0.99;
  image: "//via.placeholder.com/200x200";
}
export default function GrocerySearch() {
  const filteredProducts = [];
  const [currentProducts, setcurrentProducts] = useState([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 16;
  useEffect(() => {
    getList();
  }, []);

  const router = useRouter();
  const indexOfLastProduct = currentPage * pageSize;
  const indexOfFirstProduct = indexOfLastProduct - pageSize;
  function getList() {
    console.log("cause");
    axios
      .post("/api/product-search", {
        name: searchTerm,
        pageNum: currentPage,
        pageSize: pageSize,
      })
      .then((res) => {
        let datalist = res.data.data;
        setcurrentProducts(datalist);
        console.log(
          "商品结果",
          currentPage,
          "34444",
          res.data.data,
          currentProducts
        );
      });
  }

  // Change page
  const paginate = (pageNumber: number) => {
    setCurrentPage(pageNumber);
    getList();
  };

  //Navigate to details page
  const navigateToProductDetails = (productId: number) => {
    router.push(`/products/${productId}`);
  };

  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-3xl font-bold mb-8">Grocery Search</h1>

      {/* Search input */}
      <div className="flex mb-8">
        <Input
          type="text"
          placeholder="Search for products..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="flex-grow mr-2"
        />
        <Button onClick={() => getList()}>
          <Search className="mr-2 h-4 w-4" /> Search
        </Button>
      </div>

      {/* Product grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        {currentProducts.map((product) => (
          <Card key={product.id}>
            <CardContent className="p-4">
              <img
                src={product.image}
                alt={product.name}
                className="w-full h-48 object-cover mb-4"
              />
              <h2 className="text-xl font-semibold mb-2">{product.name}</h2>
              <p className="text-green-600 font-bold">
                ${product.price.toFixed(2)}
              </p>
            </CardContent>
            <CardFooter>
              <Button className="w-full">Add to Cart</Button>
            </CardFooter>
            <CardFooter>
              <Button
                onClick={() => navigateToProductDetails(product.id)}
                className="w-full"
              >
                View Detail
              </Button>
            </CardFooter>
          </Card>
        ))}
      </div>

      {/* Pagination */}
      <Pagination>
        <PaginationContent>
          <PaginationItem>
            <PaginationPrevious
              onClick={() => paginate(currentPage - 1)}
              className={
                currentPage === 1 ? "pointer-events-none opacity-50" : ""
              }
            />
          </PaginationItem>
          {Array.from({
            length: Math.ceil(currentProducts.length / pageSize),
          }).map((_, index) => (
            <PaginationItem key={index}>
              <PaginationLink
                onClick={() => paginate(index + 1)}
                isActive={currentPage === index + 1}
              >
                {index + 1}
              </PaginationLink>
            </PaginationItem>
          ))}
          <PaginationItem>
            <PaginationNext
              onClick={() => paginate(currentPage + 1)}
              className={
                currentPage === Math.ceil(currentProducts.length / pageSize)
                  ? "pointer-events-none opacity-50"
                  : ""
              }
            />
          </PaginationItem>
        </PaginationContent>
      </Pagination>
    </div>
  );
}
